import sys
from report_step3 import get_report
import tos
from tos import HttpMethodType
import mysql.connector
import os
from las.client import LASClient
from las.exceptions import LASError
from las.auth import StaticCredentials
from las.task import SQLTask
import  pandas as pd

# Access key 和 Secret key 可在用户火山引擎账号中查找
ak = "AKLTMmFmMzVmNmY5ZDEyNDNmNWEyZTU2MDM3Y2EzMDJlZTk"
sk = "WVdNeFpXRXdNekV4Tm1ZME5EZGxPRGc0TUdFNE1HWXdNV1ZqTkdNNU9HRQ=="
# your endpoint 和 your region 填写Bucket 所在区域对应的Endpoint。# 以华北2(北京)为例，your endpoint 填写 tos-cn-beijing.volces.com，your region 填写 cn-beijing。
endpoint = "tos-cn-beijing.ivolces.com"
region = "cn-beijing"

def execute_sql_task(ak,sk,sql):
    region = 'cn-beijing'
    endpoint = 'las.volcengineapi.com'
    client = LASClient(credentials=StaticCredentials(ak, sk), region=region,
                       endpoint=endpoint)


    try:
        # timeout 控制超时时间。。
        job = client.execute(task=SQLTask(name='sql task', query=sql, conf={}), is_sync=True,timeout=3000000)
        if job.is_success():
            result = job.get_result()
            return result
    except LASError as e:
        print(
            "Error in executing sql task. code = %s, error = %s" % ( e.code, e.info))


def add_to_mysql(version, url, types):
    # 配置数据库连接信息
    db_config = {
        'host': 'mysql-d8beb8b0655b-public.rds.volces.com',
        'user': 'user01',
        'password': 'password123!#',
        'database': 'bi_test'
    }
    # 创建数据库连接
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()

    # 假设你有一个名为 'your_table' 的表，包含 'column1', 'column2', 'column3' 等字段
    table_name = 'version_hil'

    # 假设你有一个数据字典，包含要插入的数据
    data_to_insert = {
        'version': version,
        'url': url,
        'type': types
    }

    # 构建 SQL 插入语句
    columns = ', '.join(data_to_insert.keys())
    values = ', '.join(['%s'] * len(data_to_insert))
    sql_insert = f"replace into {table_name} ({columns}) VALUES ({values})"

    # 执行插入操作
    cursor.execute(sql_insert, list(data_to_insert.values()))

    # 提交更改
    conn.commit()


def pre_signed_url(object_key, bucket_name, expires=3600 * 30 * 24):
    # endpoint = 'tos-cn-beijing.ivolces.com'
    endpoint = 'tos-cn-beijing.volces.com'
    region = 'cn-beijing'
    tos_client = tos.TosClientV2(ak, sk, endpoint, region)
    pre_signed_url_output = tos_client.pre_signed_url(HttpMethodType.Http_Method_Get, bucket=bucket_name,
                                                      key=object_key, expires=expires)
    if type(pre_signed_url_output.signed_url) == str and len(pre_signed_url_output.signed_url) > 0:
        return pre_signed_url_output.signed_url
    else:
        return ''


def upload(bucket_name, object_key, file_name):
    try:
        # 创建 TosClientV2 对象，对桶和对象的操作都通过 TosClientV2 实现
        client = tos.TosClientV2(ak, sk, endpoint, region)
        # 将本地文件上传到目标桶中
        # file_name为本地文件的完整路径。
        client.put_object_from_file(bucket_name, object_key, file_name)
    except tos.exceptions.TosClientError as e:
        # 操作失败，捕获客户端异常，一般情况为非法请求参数或网络异常
        print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
    except tos.exceptions.TosServerError as e:
        # 操作失败，捕获服务端异常，可从返回信息中获取详细错误信息
        print('fail with server error, code: {}'.format(e.code))
        # request id 可定位具体问题，强烈建议日志中保存
        print('error with request id: {}'.format(e.request_id))
        print('error with message: {}'.format(e.message))
        print('error with http code: {}'.format(e.status_code))
    except Exception as e:
        print('fail with unknown error: {}'.format(e))

def get_version(pt_jobid):
    try:
        ak = "AKLTNjI3Y2IxNzc1OGFiNGE5ZmI0YWM1Mzc5MzE3N2IxNzY"
        sk = "TkRJNE56SmxPR1EwTnpNeE5HUmlaR0V5WWpFMU5tRTVOelptWkRNM01tSQ=="

        sql = """
select
pt_version,
pkg_version
from dwd.dwd_sim_fault_injection_case_d
where pt_jobid='{}'
limit 1
              """
        sql = sql.format(pt_jobid)
        print("sql: " + sql)
        result = execute_sql_task(ak, sk, sql)
        df_injt = pd.DataFrame(result.data[1:])
        df_injt.columns = result.data[0]


        df_injt['pt_version']=df_injt['pt_version'].astype(str)
        df_injt['pkg_version'] = df_injt['pkg_version'].astype(str)
        pt_version=str(df_injt['pt_version'].iloc[0])
        pkg_version = str(df_injt['pkg_version'].iloc[0])
        return pt_version,pkg_version
    except Exception as e:
        print('data parse eth error, ', str(e))

if __name__ == '__main__':
     pt_date="20231121"
     pt_hour="15"
     pt_jobid=pt_date+pt_hour
     pt_version,pkg_version=get_version(pt_jobid)
     print(pt_version)
     print(pkg_version)
